package com.polaris.live.popup

import android.content.Context
import android.view.View
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.XPopup
import com.polaris.live.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.PopupSelectMoreCardBinding
import com.polaris.live.dialog.common.ConfirmCanalDialog
import com.polaris.live.im.sfs.PARTY_LIVESITEMICBAN
import com.polaris.live.im.sfs.PARTY_LIVESITEVIDEOBAN
import com.polaris.live.im.sfs.bean.live.LiveSiteMicMessage
import com.polaris.live.im.sfs.bean.live.LiveSiteVideoBanMessage
import com.polaris.live.im.sfs.core.SmartFoxQueueManager
import com.polaris.live.im.sfs.core.bean.resolveResponse
import com.polaris.live.net.liveService
import com.polaris.live.popup.base.BaseLiveBottomPopupView
import com.polaris.live.popup.party.InvitingSeatPopup
import com.polaris.live.resp.back_resp.BanMessageResp
import com.polaris.live.resp.back_resp.InfoOtherResp
import com.polaris.live.resp.go_resp.UserIdBean
import com.polaris.live.translation.R.string
import com.polaris.live.ui.party.widget.seat.bean.BaseSeatBean
import kotlinx.coroutines.launch

/**
 * 派对通用更多卡片
 *
 * @author Created by 半仙 on 2024/5/10/010 10:01
 */
class SelectMoreCardPopup(
    context: Context,
    private val mViewModel: BaseViewModel,
    private val mInfoUserResp: InfoOtherResp,
    private val mSeatBean: BaseSeatBean?,
    private val mBanMessageUser: List<Long>?,
    private val mAdministrators: List<Long>?,
    private val mObjectId: Long?,
    private val mHomeOwnerId: Long?,
    private val mVideoRoom: Boolean,
    private val mOnInviteOrKickSiteListener: ((isInviteUp: Boolean) -> Unit)?,
    private val mOnKickRoomListener: (() -> Unit)? = null,
    private val mOnAtClickListener: (() -> Unit)? = null,
) : BaseLiveBottomPopupView<PopupSelectMoreCardBinding>(
    context,
    { PopupSelectMoreCardBinding.bind(it) }
) {

    override fun getImplLayoutId() = R.layout.popup_select_more_card

    override fun getContentView(): View = mBinding.bottom

    override fun onCreate() {
        super.onCreate()
        mBinding = PopupSelectMoreCardBinding.bind(popupImplView)

        mBinding.tvAtText.text = mInfoUserResp.nickname

        if (mSeatBean != null) {
            mBinding.voiceLl.visibility = VISIBLE
            mBinding.videoLl.visibility = if (mVideoRoom) VISIBLE else GONE
            //判断是否禁麦
            if (mSeatBean.siteMicStatus == 2) {
                setMaiUi(true)
            } else {
                setMaiUi(false)
            }

            //判断是否禁视频
            if (mSeatBean.siteVideoStatus == 2) {
                setVideoUi(true)
            } else {
                setVideoUi(false)
            }
        } else {
            mBinding.videoLl.visibility = GONE
            mBinding.voiceLl.visibility = GONE
        }


        //判断是否禁言
        val isBanMessage = mBanMessageUser?.any { userId -> userId == mInfoUserResp.userId } ?: false
        setBanUi(isBanMessage)


        invitingOrOutSiteUi(mSeatBean == null)
        //判断是否管理员
        val isAdministrator = mAdministrators?.any { userId -> userId == mInfoUserResp.userId } ?: false
        setAdministrator(isAdministrator)
        //判断自己是不是管理员
        val selfIsAdministrator = mAdministrators?.any { userId -> userId == UserManager.getUserId() } ?: false
        if (UserManager.getUserId() != mHomeOwnerId) {
            if (selfIsAdministrator) {
                mBinding.llAdministrator.visibility = View.GONE
            }
            if (!selfIsAdministrator || isAdministrator || mInfoUserResp.userId == mHomeOwnerId) {
                mBinding.llTop.visibility = View.GONE
            }
        }

        initListener()
    }

    private fun initListener() {
        //禁麦
        mBinding.mikeSwitchBtn.setOnCheckedChangeListener { buttonView, isSelected ->
            if (buttonView.isPressed) {
                siteMic(mInfoUserResp.userId, isSelected) {
                    mBinding.mikeSwitchBtn.isChecked = it
                }
            }
        }
        //禁视频
        mBinding.videoSwitchBtn.setOnCheckedChangeListener { buttonView, isSelected ->
            if (buttonView.isPressed) {
                siteVideo(mInfoUserResp.userId, isSelected) {
                    mBinding.videoSwitchBtn.isChecked = it
                }
            }
        }
        //禁言
        mBinding.banMessageSwitchBtn.setOnCheckedChangeListener { buttonView, isChecked ->
            if (buttonView.isPressed) {
                banMessage(mInfoUserResp.userId, isChecked) {
                    mBinding.banMessageSwitchBtn.isChecked = it
                }
            }
        }
        //邀请上座或者踢出座位
        mBinding.llInviteOrKickSite.setOnSingleClickListener {
            if (mSeatBean == null) {
                XPopup.Builder(context)
                    .hasShadowBg(true)
                    .isDestroyOnDismiss(true)
                    .asCustom(InvitingSeatPopup(context) {
                        mOnInviteOrKickSiteListener?.invoke(true)
                        dismiss()
                    })
                    .show()
            } else {
                mOnInviteOrKickSiteListener?.invoke(false)
                dismiss()
            }
        }
        //踢出房间
        mBinding.llOutRoom.setOnSingleClickListener {
            mOnKickRoomListener?.invoke()
            dismiss()
        }
        //艾特他
        mBinding.llAtIt.setOnSingleClickListener {
            mOnAtClickListener?.invoke()
            dismiss()
        }
        //举报他
        mBinding.llReportIt.setOnSingleClickListener {
            GlobalPopupManager.showReport(
                context,
                mInfoUserResp.nickname,
                mViewModel,
                mInfoUserResp.userId,
                mObjectId
            )
        }
        //设置管理员
        mBinding.setAdministratorSwitchBtn.setOnSingleClickListener {
            val isChecked = mBinding.setAdministratorSwitchBtn.isChecked
            mBinding.setAdministratorSwitchBtn.isChecked = !isChecked
            administratorUpOrDown(isChecked) {
                mBinding.setAdministratorSwitchBtn.isChecked = it
                setAdministrator(it)
            }
        }
    }

    /**
     * 开关禁麦
     */
    private fun siteMic(userid: Long, mic: Boolean, onSetSiteMic: ((Boolean)) -> Unit) {
        mViewModel.viewModelScope.launch {
            val anchorId = mHomeOwnerId ?: return@launch
            try {
                val resp = SmartFoxQueueManager.sendLiveMessage(
                    PARTY_LIVESITEMICBAN,
                    LiveSiteMicMessage(userid, mic, anchorId)
                )
                val data = resp.receipt.resolveResponse<LiveSiteMicMessage>()
                if (data != null) {
                    if (data.banMic) {
                        ToastGravity.showGravity(string.prohibition_wheat_successfully)
                    } else {
                        ToastGravity.showGravity(string.successfully_opened_microphone)
                    }
                    setMaiUi(data.banMic)
                    onSetSiteMic(data.banMic)
                } else {
                    onSetSiteMic(!mic)
                    ToastGravity.showGravity(string.operation_failed)
                }
            } catch (t: Throwable) {
                onSetSiteMic(!mic)
                ToastGravity.showGravity(t.message)
            }
        }
    }

    /**
     * 开关禁视频
     */
    private fun siteVideo(userid: Long, video: Boolean, onSetSiteVideo: ((Boolean)) -> Unit) {
        mViewModel.viewModelScope.launch {
            val anchorId = mHomeOwnerId ?: return@launch
            try {
                val resp = SmartFoxQueueManager.sendLiveMessage(
                    PARTY_LIVESITEVIDEOBAN,
                    LiveSiteVideoBanMessage(userid, video, anchorId)
                )
                val data = resp.receipt.resolveResponse<LiveSiteVideoBanMessage>()
                if (data != null) {
                    if (data.ban) {
                        ToastGravity.showGravity(string.disable_camera_wheat_successfully)
                    } else {
                        ToastGravity.showGravity(string.successfully_opened_camera)
                    }
                    setVideoUi(data.ban)
                    onSetSiteVideo(data.ban)
                } else {
                    onSetSiteVideo(!video)
                    ToastGravity.showGravity(string.operation_failed)
                }
            } catch (t: Throwable) {
                onSetSiteVideo(!video)
                ToastGravity.showGravity(t.message)
            }
        }
    }

    private fun setMaiUi(isMaiBan: Boolean) {
        mBinding.root.post {
            if (isMaiBan) {
                mBinding.ivMike.alpha = 1.0f
                mBinding.tvMike.alpha = 1.0f
            } else {
                mBinding.ivMike.alpha = 0.4f
                mBinding.tvMike.alpha = 0.4f
            }
            mBinding.mikeSwitchBtn.isChecked = isMaiBan
        }
    }

    private fun setVideoUi(isVideoBan: Boolean) {
        mBinding.root.post {
            if (isVideoBan) {
                mBinding.ivVideo.alpha = 1.0f
                mBinding.tvVideo.alpha = 1.0f
            } else {
                mBinding.ivVideo.alpha = 0.4f
                mBinding.tvVideo.alpha = 0.4f
            }
            mBinding.videoSwitchBtn.isChecked = isVideoBan
        }
    }

    /**
     * 公屏禁言
     */
    private fun banMessage(userid: Long, ban: Boolean, onSetBanMessage: ((Boolean)) -> Unit) {
        mViewModel.requestLoading(
            { liveService.banMessage(BanMessageResp(userid, ban, mObjectId)) }, {
                if (it.ban) {
                    ToastGravity.showGravity(string.public_screen_ban)
                } else {
                    ToastGravity.showGravity(string.public_screen_unban)
                }
                setBanUi(it.ban)
                onSetBanMessage(it.ban)
            },
            {
                onSetBanMessage(!ban)
                ToastGravity.showGravity(it.errorMsg)
            }
        )
    }

    private fun setBanUi(isBan: Boolean) {
        mBinding.root.post {
            if (isBan) {
                mBinding.ivBanMessage.alpha = 1.0f
                mBinding.tvBanMessage.alpha = 1.0f
            } else {
                mBinding.ivBanMessage.alpha = 0.4f
                mBinding.tvBanMessage.alpha = 0.4f

            }
            mBinding.banMessageSwitchBtn.isChecked = isBan
        }
    }

    /**
     * 邀请上麦 或者 提下麦位
     * true是邀请上麦 false踢下麦
     */
    private fun invitingOrOutSiteUi(isUp: Boolean) {
        if (isUp) {
            mBinding.ivSiteUpOrDown.setImageResource(R.drawable.party_inviting_mai)
            mBinding.tvSiteUpOrDown.text = StringUtils.getString(string.inviting_to_take_seat)
        } else {
            mBinding.ivSiteUpOrDown.setImageResource(R.drawable.party_down_mai)
            mBinding.tvSiteUpOrDown.text = StringUtils.getString(string.Kick_off_the_seat)
        }
    }

    /**
     * 上管理员或者下管理    true 上      false 下
     */
    private fun administratorUpOrDown(isUp: Boolean, onIsCheckCallback: (Boolean) -> Unit) {
        if (isUp) {
            XPopup.Builder(context)
                .isDestroyOnDismiss(true)
                .asCustom(
                    ConfirmCanalDialog(
                        context,
                        StringUtils.getString(string.sure_set_administrator),
                        onConfirmCallback = {
                            mViewModel.requestLoading({
                                liveService.administratorSave(
                                    UserIdBean(mInfoUserResp.userId)
                                )
                            }, {
                                onIsCheckCallback.invoke(true)
                                ToastGravity.showGravity(StringUtils.getString(string.set_administrator_successfully))
                            }, {
                                onIsCheckCallback.invoke(false)
                                ToastGravity.showGravity(it.errorMsg)
                            })
                        }
                    )
                ).show()
        } else {
            mViewModel.requestLoading({
                liveService.administratorRemove(
                    mInfoUserResp.userId
                )
            }, {
                onIsCheckCallback.invoke(false)
                ToastGravity.showGravity(StringUtils.getString(string.set_administrator_remove))
            }, {
                onIsCheckCallback.invoke(true)
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

    private fun setAdministrator(isUp: Boolean) {
        mBinding.root.post {
            if (isUp) {
                mBinding.tvAdministrator.text =
                    StringUtils.getString(string.set_as_administrator_remove)
            } else {
                mBinding.tvAdministrator.text = StringUtils.getString(string.set_as_administrator)
            }
            mBinding.setAdministratorSwitchBtn.isChecked = isUp
        }
    }

}